import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { upload } from '@/services/api/common'

export function useDishImageUpload() {
    const fileInputRef = ref<HTMLInputElement | null>(null)
    
    const handleFileChange = async (event: Event, callback: (imageUrl: string) => void) => {
        const target = event.target as HTMLInputElement
        const file = target.files?.[0]
    
        if (file) {
            // 检查文件类型
            if (!file.type.startsWith('image/')) {
                ElMessage.error('只能上传图片文件!')
                resetFileInput(target)
                return
            }
    
            // 检查文件大小
            if (file.size > 2 * 1024 * 1024) {
                ElMessage.error('图片大小不能超过 2MB!')
                resetFileInput(target)
                return
            }
    
            try {
                const res = await upload(file)
                ElMessage.success('图片上传成功')
                callback(res.data)
            } catch (error) {
                ElMessage.error('图片上传失败')
            } finally {
                resetFileInput(target)
            }
        }
    }
    
    const triggerUpload = () => {
        if (fileInputRef.value) {
            fileInputRef.value.click()
        }
    }
    
    const resetFileInput = (target: HTMLInputElement) => {
        target.value = ''
    }
    
    return {
        fileInputRef,
        triggerUpload,
        handleFileChange,
        resetFileInput
    }
}
<template>
    <div class="edit-page">
        <!-- 菜品图片 -->
        <div class="store-header">
            <div class="cover-image-container">
                <img v-if="dishData.imageUrl" :src="dishData.imageUrl" class="cover-image" alt="菜品图片" />
                <div class="upload-placeholder" @click="triggerUpload">
                    <el-icon>
                        <Edit />
                    </el-icon>
                    <span>点击修改图片</span>
                </div>
            </div>
        </div>

        <!-- 菜品信息列表 -->
        <div class="store-info-container">
            <div class="info-item">
                <div class="label">菜品名称</div>
                <div class="value">
                    {{ dishData.name }}
                    <el-button link type="warning" size="small" @click="editField('name')">
                        <el-icon>
                            <Edit />
                        </el-icon> 修改
                    </el-button>
                </div>
            </div>

            <div class="info-item">
                <div class="label">菜品分类</div>
                <div class="value">
                    {{ dishData.categoryName }}
                    <el-button link type="warning" size="small" @click="editField('category')">
                        <el-icon>
                            <Edit />
                        </el-icon> 修改
                    </el-button>
                </div>
            </div>

            <div class="info-item">
                <div class="label">售价</div>
                <div class="value">
                    ¥{{ dishData.price }}
                    <el-button link type="warning" size="small" @click="editField('price')">
                        <el-icon>
                            <Edit />
                        </el-icon> 修改
                    </el-button>
                </div>
            </div>

            <!-- 口味信息 -->
            <div class="info-item">
                <div class="label">口味信息</div>
                <div class="value">
                    <transition-group name="flavor-list" tag="div">
                        <div v-if="dishData.flavors && dishData.flavors.length > 0" key="flavors">
                            <!-- 温度标签展示 -->
                            <div v-if="dishData.flavors.some(flavor => flavor.flavorType === '温度')" class="temperature-tags">
                                <span class="temperature-label">温度:</span>
                                <div class="tags-container">
                                    <el-tag
                                        v-for="(option, index) in getTemperatureOptions()"
                                        :key="index"
                                        closable
                                        @close="removeTemperatureOption(index)"
                                        type="warning"
                                        size="small"
                                        style="margin-right: 8px; margin-bottom: 8px;"
                                    >
                                        {{ option }}
                                    </el-tag>
                                </div>
                            </div>
                        </div>
                        <div v-else key="no-flavors" class="no-flavor">
                            <span>暂无口味信息</span>
                        </div>
                    </transition-group>
                    <el-button link type="primary" size="small" @click="addFlavor" class="add-flavor-btn">
                        <el-icon>
                            <Plus />
                        </el-icon> 添加口味
                    </el-button>
                </div>
            </div>
        </div>

        <!-- 隐藏的文件输入组件 -->
        <input type="file" ref="fileInputRef" class="hidden-file-input" @change="onFileChange" accept="image/*" />

        <!-- 编辑对话框 -->
        <el-dialog v-model="editDialog.visible" :title="editDialog.title" class="adaptive-dialog"
            :before-close="handleClose" width="400px">
            <template v-if="editDialog.field === 'name'">
                <el-input v-model="tempValue" placeholder="请输入菜品名称" />
            </template>

            <template v-else-if="editDialog.field === 'category'">
                <el-select v-model="tempValue" placeholder="请选择菜品分类" style="width: 100%;">
                    <el-option label="汤类" value="汤类"></el-option>
                    <el-option label="鱼类" value="鱼类"></el-option>
                </el-select>
            </template>

            <template v-else-if="editDialog.field === 'price'">
                <el-input v-model="tempValue" type="number" placeholder="请输入售价" />
            </template>

            <template v-else-if="editDialog.field === 'status'">
                <el-select v-model="tempValue" placeholder="请选择售卖状态" style="width: 100%;">
                    <el-option label="启售" value="onSale"></el-option>
                    <el-option label="停售" value="unSale"></el-option>
                </el-select>
            </template>

            <template v-else-if="editDialog.field === 'image'">
                <div class="image-preview" v-if="tempValue">
                    <img :src="String(tempValue)" alt="预览图片" class="preview-image" />
                </div>
                <el-button @click="triggerUpload">上传新图片</el-button>
            </template>

            <!-- 口味编辑模板 -->
            <template v-else-if="editDialog.field === 'flavor'">
                <el-form :model="tempFlavor" label-width="80px">
                    <el-form-item label="口味类型">
                        <el-input v-model="tempFlavor.flavorType" placeholder="请输入口味类型" />
                    </el-form-item>
                    <el-form-item label="口味选项">
                        <el-input v-model="tempFlavor.flavorOptions" placeholder="请输入口味选项，用逗号分隔" />
                    </el-form-item>
                    <el-form-item label="是否必选">
                        <el-switch v-model="tempFlavor.isRequired" :active-value="1" :inactive-value="0" />
                    </el-form-item>
                </el-form>
            </template>

            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="editDialog.visible = false" class="btn cancelBtn">取消</el-button>
                    <el-button type="primary" @click="saveField(editDialog.field)" color="#ffc200"
                        class="btn">保存</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Edit, Delete, Plus } from '@element-plus/icons-vue'
import type { PropType } from 'vue'
import { useDishImageUpload } from '@/utils/useDishImageUpload'
import { upload } from '@/services/api/common'

// 定义口味数据类型
interface Flavor {
    dishesId: number | null
    flavorType: string
    flavorOptions: string
    isRequired: number
    maxSelections: number
    minSelections: number
}

// 定义菜品数据类型
interface DishData {
    dishesId: number
    name: string
    imageUrl: string
    categoryName: string
    price: number
    originalPrice: number
    isAvailable: number
    description: string
    monthlySales: number
    rating: number
    ratingCount: number
    sortOrder: number
    storeId: number
    updateTime: string
    createTime: string
    flavors?: Flavor[]
}

// Props 定义
const props = defineProps({
    dish: {
        type: Object as PropType<DishData>,
        required: true,
        default: () => ({
            flavors: []
        })
    }
})

// Emits 定义
const emit = defineEmits<{
    (e: 'update:dish', dish: DishData): void
}>()

// 响应式数据
const dishData = ref<DishData>({ ...props.dish })

// 监听 props 变化
watch(() => props.dish, (newDish) => {
    dishData.value = { ...newDish }
}, { deep: true })

// 编辑对话框状态
const editDialog = reactive({
    visible: false,
    field: '',
    title: ''
})

// 文件输入引用
const fileInputRef = ref<HTMLInputElement | null>(null)

// 临时值，用于编辑时存储
const tempValue = ref<string | number>('')

// 临时口味数据
const tempFlavor = ref<Flavor>({
    dishesId: null,
    flavorType: '',
    flavorOptions: '',
    isRequired: 0,
    maxSelections: 1,
    minSelections: 0
})

// 当前编辑的口味索引
const currentFlavorIndex = ref<number | null>(null)

// 触发文件上传
const triggerUpload = () => {
    if (fileInputRef.value) {
        fileInputRef.value.click()
    }
}

// 处理文件变更
const handleFileChange = async (event: Event) => {
    const target = event.target as HTMLInputElement
    const file = target.files?.[0]

    if (file) {
        // 检查文件类型
        if (!file.type.startsWith('image/')) {
            ElMessage.error('只能上传图片文件!')
            resetFileInput(target)
            return
        }

        // 检查文件大小
        if (file.size > 2 * 1024 * 1024) {
            ElMessage.error('图片大小不能超过 2MB!')
            resetFileInput(target)
            return
        }

        try {
            const res = await upload(file)
            // 如果是直接上传图片（不是在编辑对话框中）
            if (!editDialog.visible) {
                dishData.value.imageUrl = res.data
                emit('update:dish', dishData.value)
            } else {
                tempValue.value = res.data
            }
            ElMessage.success('图片上传成功')
        } catch (error) {
            ElMessage.error('图片上传失败')
        } finally {
            resetFileInput(target)
        }
    }
}

// 重置文件输入框
const resetFileInput = (target: HTMLInputElement) => {
    target.value = ''
}

// 编辑字段